<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Acl
 *
 * @author duc.do
 */
class Dmd_Acl extends Zend_Acl
{
    public function __construct() {

         //Add a new role called "guest"
        $this->addRole(new Zend_Acl_Role('guest'));
        
        //Add a resource called page
        $this->add(new Zend_Acl_Resource('front/login'));
        $this->add(new Zend_Acl_Resource('front/error'));
        
        $this->allow('guest', 'front/login', 'index');
        $this->allow('guest', 'front/login', 'logout');
        $this->allow('guest', 'front/error', 'error');
    }
    
    public function setRoles($roles)
    {
        if (is_array($roles)) {
            foreach ($roles as $role) {
                $roleName = $role['name'];
                if (!$this->hasRole($roleName)) {
                    $this->addRole(new Zend_Acl_Role($roleName), 'guest');

                    foreach ($role['privileges'] as $privilege)
                    {
                        $resourceName = $privilege['resource']['module'].DS.$privilege['resource']['controller'];
                        $privilegeName = $privilege['resource']['action'];

                        if(!$this->has($resourceName)) {
                            $this->add(new Zend_Acl_Resource($resourceName));
                        }
                        if ($privilege['_isAllowed']==1) {
                            $this->allow($roleName, $resourceName, $privilegeName);
                        } else {
                            $this->deny($roleName, $resourceName, $privilegeName);                    
                        }
                    }
                }
            }
        }
    }

    public function isAllowed($roles = null, $resource = null, $privilege = null) {
        $result = false;
        if (is_array($roles)) {
            $ret = false;
            foreach ($roles as $role) {
                $ret = $ret || ($this->has($resource) ? parent::isAllowed($role, $resource, $privilege) : false);
            }
            $result = $ret;
        } else {
            $result = $this->has($resource) ? parent::isAllowed($roles, $resource, $privilege) : false;
        }
        return $result;
    }
}

